using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using DNAide.Configuration;

namespace DNAide.Web
{
	/// <summary>
	/// IHttpModule to handler application level errors
	/// </summary>
	public class HttpErrorModule : IHttpModule
	{
		public void Init(HttpApplication context)
		{
			if (context == null)
				return;

			if (!DNAideConfigurationSettings.Web.HttpErrorModule.Enabled)
				return;

			context.Error += new EventHandler(context_Error);
		}

		void context_Error(object sender, EventArgs e)
		{
			HttpApplication app = sender as HttpApplication;

			if (app == null || app.Server == null)
				return;

			Exception error = app.Server.GetLastError();

			if (error != null)
			{
				int code = 500;

				if (error is HttpException)
				{
					code = (error as HttpException).GetHttpCode();
				}

				IEnumerator<HttpErrorModuleRuleConfig> errorEnum = DNAideConfigurationSettings.Web.HttpErrorModule.Rules.GetEnumerator();
				while (errorEnum.MoveNext())
				{
					if (errorEnum.Current.Code == code)
					{
						if (HandleError(code, error))
						{
							app.Server.ClearError();
						}

						app.Context.Handler = PageParser.GetCompiledPageInstance(
							errorEnum.Current.HandlerPage,
							app.Server.MapPath(errorEnum.Current.HandlerPage),
							app.Context);

						app.Context.Handler.ProcessRequest(app.Context);
						app.CompleteRequest();
					}
				}
			}
		}

		/// <summary>
		/// Handle the specified error. Server error will be cleared by default.
		/// </summary>
		/// <param name="code">Http error code being thrown.</param>
		/// <param name="error">Exception containing details of error.</param>
		/// <returns><code>true</code> if server error should be cleared or <code>false</code> if not.</returns>
		protected virtual bool HandleError(int code, Exception error)
		{
			return true;
		}

		/// <summary>
		/// Dispose.
		/// </summary>
		public void Dispose()
		{
		}
	}
}
